import axios from 'axios'
import { MessageBox, Message } from 'element-ui'
import store from '@/store'
import router from '@/router'
import { getToken } from '@/utils/auth'
import $baseUrl from '@/utils/baseURL'


// create an axios instance
const service = axios.create({
  baseURL: $baseUrl.webServiceUrl,
  timeout: 5000
})
const apiSpecialStr = 'v3/'
function getBaseUrl(url) {
  let newBaseURL = ''
  if (url.indexOf(apiSpecialStr) !== -1) {
    newBaseURL = $baseUrl.agricultureServiceUrl //农业平台
  } else {
    newBaseURL = $baseUrl.webServiceUrl //水产养殖系统
  }
  if (url.indexOf('/fish/public/') !== -1) {
    newBaseURL = $baseUrl.fileServiceUrl
  }
  let databaseName = sessionStorage.getItem('databaseName');
  // databaseName = 'DB_FISH_BUSINESS';
  return { baseURL: newBaseURL, databaseName: databaseName }
}
service.interceptors.request.use(
  config => {
    const baseURLObj = getBaseUrl(config.url);
    config.baseURL = baseURLObj.baseURL
    if (getToken()) {
      if (config.url.indexOf('/warehousingEntry/addList') !== -1 || config.url.indexOf('outboundOrder/addList') !== -1) {
        console.log(config.url)
      } else if (config.url.indexOf('v3/') !== -1) {
        if (config.method == 'get' && config.url.indexOf('/templateTenant') == -1) {
          config.params = { ...config.params, organizationNo: sessionStorage.getItem('organizationNo') };
        } else if (config.method == 'post' && config.url.indexOf('/templateTenant') == -1) {
          config.data = { ...config.data, organizationNo: sessionStorage.getItem('organizationNo') };
        }
      }

      config.headers['accessToken'] = store.getters.token || sessionStorage.getItem('token') || getToken();
      config.headers['Organizationno'] = sessionStorage.getItem('organizationNo');
      config.headers['Organizationlist'] = sessionStorage.getItem('organizationNoList');
      config.headers['Virtualsystemno'] = sessionStorage.getItem('virtualSystemNo');
      config.headers['Sysdatabasename'] = baseURLObj.databaseName;
      config.headers['Databasename'] = baseURLObj.databaseName;
      config.headers['BreedType'] = sessionStorage.getItem('breedType');
    }
    if (config.url.includes('/warehousingEntry/addList')) {
      // 导入文件设置请求头
      config.headers["Content-Type"] = "application/json"
    }
    if (config.url.includes('/employee/importExcel')) {
      // 导入文件设置请求头
      config.headers["Content-Type"] = "multipart/form-data"
    }
    if (config.url.includes('/web/login')) {
      // 导入请求头
      config.headers["Content-Type"] = "application/x-www-form-urlencoded"
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)
service.interceptors.response.use(
  response => {
    if (response.status == 200) {
      const res = response.data
      //res=='123456' 是重置密码/接口返回数据为123456
      if (res.code == 200 || res.code == 1 || res.success == true || res == '123456') {
        return res
      } else {
        return Promise.reject(res.msg || response.status + ':Error');
      }
    } else {
      return Promise.reject(errorInfo(response.status) || 'Error');
    }

  },
  error => {
    // 为了规避后端报错，注释这里其实是个不合理的；
    let msg = '接口异常'
    if (JSON.stringify(error).indexOf('401') !== -1) {
      msg = '认证过期请重新登录'
      MessageBox.confirm('认证已过期请重新登录！', '提示', {
        confirmButtonText: '确定',
        type: 'warning'
      }).then(() => {
        logout();
      })
      return
    } else if (JSON.stringify(error).indexOf('413') !== -1) {
      msg = '上传资源过大请重新上传！'
    }
    let errResponse = JSON.parse(JSON.stringify(error))?.response
    let errData = errResponse ? errResponse.data : {}
    let errMsg = errData.message
    // console.log(JSON.parse(JSON.stringify(error)), errResponse)
    Message({
      message: errMsg || msg,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)
async function logout() {
  await store.dispatch('user/logout')
  router.push(`/login`)
}
//处理报错
function errorInfo(code) {
  let msg = ''
  if (code == 404) {
    msg = '404:服务器找不到请求的网页'
  } else if (code == 500) {
    msg = '500:服务器内部错误'
  } else if (code == 501) {
    msg = '501:尚未实施'
  } else if (code == 502) {
    msg = '502:错误网关'
  } else if (code == 503) {
    msg = '503:服务器不可以'
  } else if (code == 504) {
    msg = '504:网关超时'
  } else if (code == 505) {
    msg = '505:HTTP 版本不受支持'
  } else if (code == 401) {
    msg = '401:token已经过期请重新登录'
  } else {
    msg = '接口异常'
  }
  Message({
    message: msg || 'Error',
    type: 'error',
    duration: 5 * 1000
  })
  return msg
}
// 封装get请求
export function get(url, params = {}) {
  params.t = new Date().getTime(); // get方法加一个时间参数,解决ie下可能缓存问题.
  console.log(url, 'get', params)
  return service({
    url: url,
    method: "get",
    params
  });
}

// 封装post请求
export function post(url, data = {}) {
  // 默认配置
  let sendObject = {
    url: url,
    method: "post",
    data
  };
  console.log(url, 'post', data)

  sendObject.data = JSON.stringify(data);
  return service(sendObject);
}

export default service
